package com.cynen.p42u.task;

import org.apache.http.client.HttpClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.downloader.HttpClientDownloader;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.proxy.Proxy;
import us.codecraft.webmagic.proxy.SimpleProxyProvider;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;

/**
 * 代理的演示demo
 * 好像不太好用.
 */

// @Component
public class ProxyUse implements PageProcessor {

    @Scheduled(initialDelay = 1000,fixedDelay = 10*1000)
    public void entrance(){
        // 代理需要在downloader里面设置.
        HttpClientDownloader downloader = new HttpClientDownloader();
        downloader.setProxyProvider(SimpleProxyProvider.from(new Proxy("110.243.8.186",9999,"18923363349","cynen2020")));

        Spider.create(new ProxyUse())
                .addUrl("https://www.ip.cn/")
                .setDownloader(downloader)
                .run();
    }


    @Override
    public void process(Page page) {
        List<Selectable> nodes = page.getHtml().css("div#result p").nodes();
        for (Selectable selectable:nodes){
            System.out.print(selectable.css("p","text"));
            System.out.println(selectable.css("p code","text"));
        }
    }

    private Site site = Site.me().addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36");

    @Override
    public Site getSite() {
        return site;
    }
}
